package io;

import org.junit.Test;

import java.io.*;

/**
 * @description: 测试缓冲流，速度相比文件流更快
 *   private static int DEFAULT_BUFFER_SIZE = 8192;
 *
 * @author: apple
 * @date:  2021/12/25 9:05 下午
 * @version 1.0
 **/
public class BufferTest {


    @Test
    public void test1() throws IOException {

        // 创文件
        File f1 = new File("test.txt");
        File f2 = new File("test2.txt");

        // 创节点流
        FileInputStream in = new FileInputStream(f1);
        OutputStream out = new FileOutputStream(f2);

        // 创缓冲流
        BufferedInputStream bin = new BufferedInputStream(in);
        BufferedOutputStream bout = new BufferedOutputStream(out);

        byte[] buffer = new byte[5];
        int len;
        while ((len = bin.read(buffer)) != -1) {
            bout.write(buffer, 0, len);
        }

        // 关闭外层流的时候，内层流也会关闭
        bin.close();
        bout.close();

    }

    @Test
    public void test2() throws IOException {

        BufferedReader reader = new BufferedReader(new FileReader(new File("test.txt")));
        BufferedWriter writer = new BufferedWriter(new FileWriter(new File("test5.txt")));

        // 方式一：
      /*  char[] buffer = new char[5];
        int len;
        while ((len = reader.read(buffer)) != -1 ) {
            writer.write(buffer, 0,len);
        }*/

        // 方式二
        String str = null;
        while ((str = reader.readLine()) != null) {
            writer.write(str + "\n");
        }

        reader.close();
        writer.close();
    }
}
